// 专业选项
const selectProfessionMajor = document.querySelector('select[name="professionMajor"]')
// 退出按钮
const cancel = document.querySelector('.cancel')
// 确认按钮
const sure = document.querySelector('.sure')
const inputs = document.querySelectorAll('.certification input')
const selects = document.querySelectorAll('.certification select')

// 获取所有专业
async function getAllProfessionMajor() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/StudentAndTeacher/Certification/getAllProfessionMajor'
  })).data.data
  selectProfessionMajor.innerHTML = result.map(e => {
    return `<option value="${e.id}">${e.name}</option>`
  }).join('')
}

getAllProfessionMajor()

// 退出认证
cancel.addEventListener('click', () => {
  const back = +confirm('退出注册')
  if (back) {
    location.href = '../../../Login/index.html?result=0'
  }
})

// 确认认证
sure.addEventListener('click', async () => {
  const name = inputs[0].value    //姓名
  if (!name) {
    alert('姓名不能为空')
    return
  }
  // 性别
  const radio = document.querySelector("input[type='radio']:checked")
  if (!radio) {
    alert('请选择性别')
    return
  }
  const gender = radio.id === 'man' ? '1' : '0'
  // 生日
  const birthday = inputs[3].value
  if (birthday === null || new Date(birthday) > Date.now()) {
    alert('生日不合法')
    return
  }
  // 居住地
  const location = inputs[4].value
  if (!/^.{1,30}$/.test(location)) {
    alert('居住地描述必须在1到30词之间')
    return
  }
  // 邮箱
  const email = inputs[5].value
  if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
    alert('邮箱不符合规范')
    return
  }
  // 身份证号
  const idCard = inputs[6].value
  if (! /^\d{17}[\dX]$/.test(idCard)) {
    alert('身份证格式错误')
    return
  }
  const majorProgramId = selects[0].value
  const degree = selects[1].value
  // 获取专业所属院系号
  const facultiesId = (await axios({
    url: 'http://127.0.0.1:8080/StudentAndTeacher/Certification/getFacultiesIdByMajorProgramId',
    params: {
      id: majorProgramId
    }
  })).data.data
  // 获取专业人数号
  const num = (await axios({
    url: 'http://127.0.0.1:8080/StudentAndTeacher/Certification/getMajorNum',
    params: {
      id: majorProgramId
    }
  })).data.data
  // 拼接学号
  const studentId = facultiesId + majorProgramId + num
  localStorage.setItem('id', studentId)
  // 上传认证数据
  axios({
    url: 'http://127.0.0.1:8080/StudentAndTeacher/Certification/uploadStudentCertification',
    method: 'POST',
    data: {
      id: studentId,
      name,
      gender,
      birthday,
      location,
      email,
      idCard,
      facultiesId,
      majorProgramId,
      degreeId: degree
    }
  }).then(() => {
    document.location.href = '../../../Login/index.html?result=1'    //跳转页面
  }).catch(() => {
    alert('已注册')
  })
})


